<template>
  <div class="makePlan app-container">
    <div class="make_plan_box">
      <div class="make_plan_top">
        <div style="font-size: 16px;margin-bottom: 20px;" class="big_title_style">
          制定方案
        </div>
        <div class="project_search">
          <el-input v-model.trim="keyWord" size="small" clearable placeholder="请输入关键词搜索"></el-input>
          <el-button type="primary" size="small" style="margin-left: 20px;" @click="toSearchData">搜索</el-button>
        </div>
      </div>

      <el-tabs class="project_tabs_type" v-model="activeName" type="card" @tab-click="handleClick">
        <el-tab-pane :label="item.label" :name="item.value + ''" v-for="(item, index) in categoryList" :key="index">
          <el-button-group class="mb10" v-if="item.children && item.children.length > 0">
            <el-button :type="val.isSelect ? 'primary' : ''" v-for="(val, idx) in item.children" class="mb10"
              style="margin-right: 10px" :key="val.value" size="small" @click="toSelectCate(index, idx)">{{ val.label
              }}</el-button>
          </el-button-group>
        </el-tab-pane>
      </el-tabs>

      <div class="show_project_card">
        <div :class="['project_card_item', item.isSelect && 'project_card_item_act']" v-for="(item, idx) in dataList"
          :key="idx" @click="toSelectProject(idx)">
          <!-- <div class="project_card_item_select"
            v-if="item.isSelect">
            <i class="el-icon-check"></i>
          </div> -->
          <div class="project_card_item_img"> <img :src="item.itemMainImage" alt=""> </div>
          <div class="project_card_item_info">
            <div class="project_card_item_name mb10">{{ item.serviceName }}</div>
            <div class="project_card_item_tags">
              <el-tag size="mini" class="project_card_item_tag" v-if="item.isLockDevice == '1'">设备</el-tag>
              <el-tag size="mini" class="project_card_item_tag" v-if="item.isDdl && item.isDdl == '1'">叠叠乐</el-tag>
            </div>
            <div class="project_card_item_price">￥{{ item.priceStr }}</div>
          </div>
        </div>
        <el-empty v-if="dataList.length == 0" style="margin: 0 auto" description="暂无数据"></el-empty>
      </div>
      <pagination :total="total" :page.sync="pageNum" :limit.sync="pageSize" :pageSizes="[12, 24, 48]"
        @pagination="getProjectPlan" />
    </div>
    <div class="custmer_info_box">
      <div class="custmer_info_box_content">
        <div style="font-size: 16px;margin-bottom: 20px;" class="big_title_style">
          客户信息
        </div>
        <div class="show_customer_phone">
          <div class="show_customer_phone_label">客户搜索</div>
          <el-select v-model="customerPhone" ref="agentSelect" filterable remote reserve-keyword
            placeholder="请输入手机号码或用户名称" :remote-method="remoteMethod" :loading="selectLoading" style="width: 440px"
            @change="changeSelectPhone" @hook:mounted="cancalReadOnly" @visible-change="cancalReadOnly">
            <el-option v-for="item in phoneList" :key="item.customerUid" :label="`${item.phone} (${item.customerName})`"
              :value="item.customerUid">
            </el-option>
          </el-select>
        </div>
        <el-card class="box-card" style="margin-bottom: 30px" :body-style="{ paddingBottom: '15px' }" v-if="customerInfo">
          <div class="show_customer_info">
            <div class="show_customer_header"> <img :src="customerInfo.headImage" alt=""> </div>
            <div class="show_customer_info_box">
              <div class="show_customer_info_top">
                <div class="show_customer_name">{{ customerInfo.customerName }}</div>
                <el-tag type="danger" class="ml10" size="mini">{{ customerInfo.levelName || '--' }}</el-tag>
              </div>
              <div class="show_customer_phone">{{ customerInfo.phone }}</div>
            </div>
          </div>
        </el-card>
        <div style="font-size: 16px;margin-bottom: 20px;" class="big_title_style mt20">
          结算信息
        </div>
        <el-table :data="selectProject" class="selltementInfo" border>
          <el-table-column label="项目名称" prop="serviceName" align="center" show-overflow-tooltip></el-table-column>
          <el-table-column label="SKU" width="130" align="center">
            <template slot-scope="scope">
              <el-select v-model="scope.row[`skuId_${scope.row.skuIdCount}`]" placeholder="请选择" style="width: 100px"
                v-if="scope.row.serviceType == 'service' && scope.row.type == '1'" size="small"
                @change="changeItemSkuId(scope.row, $event)">
                <el-option v-for="item in scope.row.skuList" :key="item.skuId" :label="item.skuName" :value="item.skuId">
                </el-option>
              </el-select>
              <span v-else>无sku</span>
            </template>
          </el-table-column>
          <el-table-column label="单价" width="80" align="center">
            <template slot-scope="scope">
              <span v-if="scope.row.serviceType == 'service'">
                {{ scope.row.type == '1' ? scope.row.itemSettlementPriceStr : scope.row.priceStr }}
              </span>
              <span v-else>{{ scope.row.priceStr }}</span>
            </template>
          </el-table-column>
          <el-table-column label="数量" width="130" align="center">
            <template slot-scope="scope">
              <el-input-number v-model.trim="scope.row.selectNum" size="small" :min="1"
                style="width: 100px"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column align="center" width="60">
            <template slot-scope="scope">
              <i class="el-icon-delete item_delete_project" @click="toDeleteProject(scope)"></i>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="project_settle">
        <div class="project_settle_info">
          <div class="project_settle_info_number">已选择{{ selectProject.length }}个项目</div>
          <div class="project_settle_info_price">
            应收款：<span class="project_settle_info_price_txt">￥{{ selltementPriceStr }}</span>
          </div>
        </div>
        <div class="project_settle_opt">
          <el-button size="small" @click="toBack" v-if="fromType == 'work'">返回</el-button>
          <el-button size="small" type="primary" @click="toSave">保存</el-button>
        </div>
      </div>
    </div>

    <el-dialog title="" :visible.sync="dialogVisible" width="300px" :show-close="false" :close-on-press-escape="false"
      :close-on-click-modal="false">
      <div class="save_success">
        <i class="el-icon-circle-check"></i>
        <div class="save_success_txt">保存成功</div>
      </div>
      <div class="to_opt_btn">
        <el-button @click="toBackWork" class="mb10 to_opt_btn_item">{{ fromType == 'work' ? '返回工作台' : '关闭' }}</el-button>
        <el-button type="primary" @click="toViewOrder" class="to_opt_btn_item">查看订单</el-button>
      </div>

    </el-dialog>
  </div>
</template>

<script>
import {
  projectCategory,
  getMakePlan,
  phoneGetUser,
  serviceGetSku,
  createOrderPC
} from "@/api/service/makePlan";

export default {
  data () {
    return {
      keyWord: '',
      activeName: '0',
      dialogVisible: false,
      selectLoading: false,
      customerPhone: '',
      categoryList: [
        {
          label: '全部分类',
          value: '0',
          children: []
        }
      ],
      fromType: 'consultOrder',
      total: 0,
      pageNum: 1,
      pageSize: 12,
      parentCategory: '',
      childCategory: '',
      dataList: [],
      selectProject: [],
      phoneList: [],
      customerInfo: null,
      detailId: '',
      skuIdCount: 10
    }
  },
  computed: {
    selltementPriceStr () {
      let priceStr = 0
      this.selectProject.forEach(item => {
        if (item.serviceType == 'service' && item.type == '1') {
          priceStr += parseFloat(item.itemSettlementPriceStr * item.selectNum)
        } else {
          priceStr += parseFloat(item.priceStr * item.selectNum)
        }
      })

      if (priceStr) {
        return priceStr.toFixed(2)
      }
      return priceStr
    }
  },
  created () {
    // if (this.$route.query.type) {
    //   this.fromType = this.$route.query.type
    // }
    // if (this.$route.query.phone) {
    //   this.customerPhone = this.$route.query.phone
    // }

    // this.getProjectCategory()
    // this.getProjectPlan()
  },
  activated () {
    if (this.$route.query.type) {
      this.fromType = this.$route.query.type
    }
    if (this.$route.query.phone) {
      this.customerPhone = this.$route.query.phone
    }

    this.getProjectCategory()
    this.getProjectPlan()
  },
  methods: {
    cancalReadOnly (onOff) {
      this.$nextTick(() => {
        if (!onOff) {
          const Selects = this.$refs
          if (Selects.agentSelect) {
            const input = Selects.agentSelect.$el.querySelector('.el-input__inner')
            input.removeAttribute('readonly')
          }
        }
      })
    },
    changeItemSkuId (row, uid) {
      let skuList = row.skuList
      this.selectProject.forEach(item => {
        if (item.serviceId == row.serviceId) {
          skuList.forEach(val => {
            if (item[`skuId_${item.skuIdCount}`] == val.skuId) {
              item.itemSettlementPriceStr = val.itemFavorablePrice ? val.itemFavorablePriceFmt : val.itemPriceFmt
            }
          })
        }
      })
    },
    toDeleteProject ({ $index }) {
      // let serviceId = row.serviceId, serviceType = row.serviceType
      // this.dataList.forEach((item, index) => {
      //   if (item.serviceId == serviceId && item.serviceType == serviceType) {
      //     item.isSelect = false
      //   }
      // })

      // let arr = this.dataList.filter(v => v.isSelect)
      this.selectProject.splice($index, 1)
    },
    async changeSelectPhone (uid) {
      this.phoneList.forEach(item => {
        if (item.customerUid == uid) {
          this.customerInfo = item
        }
      })
    },
    toSelectProject (idx) {
      if (!this.customerInfo) {
        this.msgError('请先选择顾客')
        return
      }
      let serviceId = this.dataList[idx].serviceId, serviceType = this.dataList[idx].serviceType
      let selectItem = null
      let serviceCancelId = '', cardCancelId = ''
      this.dataList.forEach((item, index) => {
        if (item.serviceId == serviceId && item.serviceType == serviceType) {
          // if (item.isSelect) {
          //   item.isSelect = false
          // if (item.serviceType == 'service') {
          //   serviceCancelId = item.serviceId
          // } else {
          //   cardCancelId = item.serviceId
          // }
          // } else {
          //   item.isSelect = true

          // }
          let saveItem = JSON.parse(JSON.stringify(item))

          if (item.serviceType == 'service') {
            if (item.skuList.length == 0) {
              this.getSkuData(saveItem, serviceId)
            } else {
              selectItem = saveItem
              saveItem[`skuId_${this.skuIdCount}`] = ''
              saveItem[`skuIdCount`] = this.skuIdCount
              this.skuIdCount++
            }
            if (selectItem) {
              selectItem.selectNum++
              this.selectProject.push(selectItem)
            }
          } else {
            // selectItem = saveItem
            let isZeroItem = false
            this.selectProject.forEach(val => {
              if (saveItem.serviceId == val.serviceId && saveItem.serviceType == val.serviceType) {
                val.selectNum++
                isZeroItem = true
              }
            })
            if (!isZeroItem) {
              saveItem.selectNum++
              this.selectProject.push(saveItem)
            }
          }

        }
      })

      // let arr = this.dataList.filter(v => v.isSelect)
      // let list = [...this.selectProject, ...arr]
      // let serviceIds = [], cardIds = [], datas = []
      // list.forEach(item => {
      //   if (item.serviceType == 'service') {
      //     if (serviceIds.indexOf(item.serviceId) < 0 && item.serviceId != serviceCancelId) {
      //       serviceIds.push(item.serviceId)
      //       datas.push(item)
      //     }
      //   } else {
      //     if (cardIds.indexOf(item.serviceId) < 0 && item.serviceId != cardCancelId) {
      //       cardIds.push(item.serviceId)
      //       datas.push(item)
      //     }
      //   }
      // })

      // this.selectProject = datas
    },
    async getSkuData (item, uid) {
      let res = await serviceGetSku(uid)
      if (res) {
        item.skuList = res.data
        item[`skuId_${this.skuIdCount}`] = ''
        item[`skuIdCount`] = this.skuIdCount
        this.skuIdCount++
        if (res.data.length == 0) {
          let isZeroItem = false
          this.selectProject.forEach(val => {
            if (item.serviceId == val.serviceId && item.serviceType == val.serviceType) {
              val.selectNum++
              isZeroItem = true
            }
          })
          if (!isZeroItem) {
            item.selectNum++
            this.selectProject.push(item)
          }
        } else {
          item.selectNum++
          this.selectProject.push(item)
        }
        this.$forceUpdate()
      }
    },
    async getProjectCategory () {
      this.categoryList = [
        {
          label: '全部分类',
          value: '0',
          children: []
        }
      ]
      let res = await projectCategory()
      if (res) {
        let { data } = res
        data.forEach(item => {
          if (item.children && item.children.length > 0) {
            item.children.forEach(val => {
              val.isSelect = false
            })
          }
        })
        this.categoryList.push(...data)
      }
    },
    toSearchData () {
      this.pageNum = 1
      this.getProjectPlan()
    },
    toSelectCate (index, idx) {
      this.categoryList.forEach((item, sIndex) => {
        if (item.children) {
          if (index == sIndex) {
            item.children.forEach((val, sIdx) => {
              if (idx == sIdx) {
                if (!val.isSelect) {
                  val.isSelect = true
                  this.childCategory = val.value
                } else {
                  val.isSelect = false
                  this.childCategory = ''
                }
              } else {
                val.isSelect = false
              }
            })
          } else {
            item.children.forEach(val => {
              val.isSelect = false
            })
          }
        }
      })
      this.pageNum = 1
      this.getProjectPlan()
    },
    async getProjectPlan () {
      let res = await getMakePlan({
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        parentCategory: this.parentCategory,
        childCategory: this.childCategory,
        keyWord: this.keyWord
      })
      if (res) {
        this.total = res.total
        let data = res.rows
        data.forEach(item => {
          item.selectNum = 0
          item.isSelect = false
          // item.skuId = ''
          item.skuList = []
          item.itemSettlementPriceStr = 0
          this.selectProject.forEach(val => {
            if (item.serviceId == val.serviceId) {
              item.isSelect = true
            }
          })
        })
        this.dataList = data
      }
    },
    handleClick (tab, event) {
      this.activeName = tab.name
      if (tab.name == '0') {
        this.parentCategory = ''
      } else {
        this.parentCategory = tab.name
        this.childCategory = ''
        this.categoryList.forEach(item => {
          if (item.children) {
            item.children.forEach(val => {
              val.isSelect = false
            })
          }
        })
      }
      this.pageNum = 1
      this.getProjectPlan()
    },
    toBack () {
      this.$store.dispatch("tagsView/delView", this.$route);
      if (this.fromType == 'work') {
        if (this.$route.query.showType == 'life') {
          this.$router.push({
            path: "/store/workbench/life",
            query: {
              t: Date.now()
            }
          });
        } else {
          this.$router.push({
            path: "/store/workbench/medicine",
            query: {
              t: Date.now()
            }
          });
        }
      }
    },
    toSave () {
      let list = [], isSelectSku = true
      this.selectProject.forEach(item => {
        if (item.type == '1' && !item[`skuId_${item.skuIdCount}`]) {
          isSelectSku = false
        }
        list.push({
          serviceType: item.serviceType,
          itemNumber: item.selectNum,
          serviceId: item.serviceId,
          skuId: item[`skuId_${item.skuIdCount}`] ? item[`skuId_${item.skuIdCount}`] : ''
        })
      })

      if (!isSelectSku) {
        this.msgError('请选择项目sku')
        return
      }

      this.$confirm('确认保存项目?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        createOrderPC({
          countPrice: this.selltementPriceStr,
          customerUid: this.customerInfo.customerUid,
          storeId: this.$route.query.storeId,
          list
        }).then(res => {
          // this.msgSuccess('保存成功')
          this.detailId = res.data.orderUid
          this.dialogVisible = true
        })
      }).catch(() => {

      });
    },
    toBackWork () {
      this.dialogVisible = false
      this.toBack()
    },
    toViewOrder () {
      this.dialogVisible = false
      this.$router.push({
        path: '/store/workbench/orderDetail',
        query: {
          detailId: this.detailId
        }
      })
    },
    remoteMethod (query) {
      if (query !== '') {
        this.selectLoading = true;
        setTimeout(() => {
          phoneGetUser({ name: query })
            .then(res => {
              this.selectLoading = false;
              this.phoneList = res.data
            })
            .catch(() => { })
        }, 200);
      } else {
        // this.options = [];
      }
    }
  }
}
</script>

<style lang="scss">
.makePlan {
  .selltementInfo {
    .el-select .el-input__inner {
      text-align: center;
    }
  }
}
</style>
<style lang="scss" scoped>
.make_plan_top {
  display: flex;
  align-items: center;

  .project_search {
    display: flex;
    align-items: center;
    margin-left: 40px;
    margin-bottom: 20px;
  }
}

img {
  display: block;
  width: 100%;
  height: 100%;
}

::v-deep .el-input-number .el-input__inner {
  text-align: center;
}

.makePlan {
  display: flex;
  height: 100%;

  .make_plan_box {
    background-color: #fff;
    flex: 1;
    padding: 15px;
    height: 100%;
    overflow-y: auto;
    margin-right: 20px;

    .show_project_card {
      display: flex;
      flex-wrap: wrap;
      width: 100%;

      .project_card_item {
        width: calc((100% - 40px) / 3);
        display: flex;
        padding: 10px;
        border-radius: 4px;
        box-shadow: 0 0 10px 5px rgba(0, 0, 0, 0.05);
        border: 1px solid #eee;
        margin-bottom: 20px;
        cursor: pointer;
        position: relative;

        &:not(:nth-child(3n)) {
          margin-right: 20px;
        }

        .project_card_item_select {
          position: absolute;
          top: 0;
          right: 0;
          height: 16px;
          width: 16px;
          border-radius: 4px;
          background-color: #5da9ef;
          font-size: 12px;
          color: #fff;
          text-align: center;
          line-height: 16px;
        }

        .project_card_item_img {
          width: 80px;
          height: 80px;
          border-radius: 4px;
          overflow: hidden;
          margin-right: 10px;
          background-color: #f9f9f9;
        }

        .project_card_item_info {
          flex: 1;
          overflow: hidden;

          .project_card_item_name {
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }

          font-size: 14px;
          color: #333;

          .project_card_item_tags {
            min-height: 34px;
          }

          .project_card_item_tag {
            margin: 0 8px 8px 0;
          }
        }
      }

      .project_card_item_act {
        border: 1px solid #5da9ef;
      }
    }
  }

  .custmer_info_box {
    padding: 15px;
    width: 540px;
    background-color: #fff;
    height: 100%;
    position: relative;
    padding-bottom: 80px;
    overflow: hidden;

    .custmer_info_box_content {
      width: 100%;
      height: 100%;
      overflow: auto;
    }

    .show_customer_phone {
      display: flex;
      align-items: center;
      margin-bottom: 10px;

      .show_customer_phone_label {
        width: 72px;
        font-size: 14px;
        color: #333;
        margin-right: 10px;
      }
    }

    .show_customer_info {
      display: flex;
      align-items: center;

      .show_customer_header {
        width: 50px;
        height: 50px;
        border-radius: 50%;
        margin-right: 16px;
        background-color: #fff;
        border: 1px solid #eee;
      }

      .show_customer_info_box {
        flex: 1;
        overflow: hidden;
      }

      .show_customer_info_top {
        display: flex;
        align-items: center;
        margin-bottom: 10px;

        .show_customer_name {
          font-size: 12px;
          color: #333;
        }
      }

      .show_customer_phone {
        font-size: 12px;
        color: #999;
      }
    }

    .item_delete_project {
      font-size: 16px;
      color: #999;
      cursor: pointer;
    }

    .project_settle {
      position: absolute;
      bottom: 0;
      left: 0;
      width: 100%;
      height: 80px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      border-top: 1px solid #eee;
      padding: 15px;

      .project_settle_info {
        .project_settle_info_number {
          font-size: 14px;
          color: #333;
          margin-bottom: 10px;
        }

        .project_settle_info_price {
          font-size: 14px;
          color: #333;

          .project_settle_info_price_txt {
            color: #c03639;
          }
        }
      }
    }
  }
}

::v-deep .el-dialog {
  margin-top: 15vh !important;
}

.save_success {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 0px 0 40px;

  .el-icon-circle-check {
    font-size: 40px;
    color: #30b08f;
    font-weight: 600;
  }

  .save_success_txt {
    font-size: 20px;
    color: #333;
    margin-top: 16px;
  }
}

.to_opt_btn {
  .to_opt_btn_item {
    display: block;
    width: 100%;

    &:last-child {
      margin: 0;
    }
  }
}
</style>